package application

import (
	"context"
	"github.com/edgexfoundry/edgex-go/internal/app/core/metadata/container"
	"github.com/edgexfoundry/edgex-go/internal/app/models"
	"github.com/edgexfoundry/edgex-go/internal/pkg/correlation"
	bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v2/bootstrap/container"
	"github.com/edgexfoundry/go-mod-bootstrap/v2/di"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/errors"
)

func TransportAdd(deviceId string, d models.Transport, ctx context.Context, dic *di.Container) (string, errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	s, err := dbClient.TransportAdd(deviceId, d)
	if err != nil {
		return "", err
	}
	lc.Debugf("transport add on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	return s, nil
}

func TransportGetByDeviceId(deviceId string, offset, limit int, ctx context.Context, dic *di.Container) ([]models.Transport, uint32, errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	transports, totalCount, err := dbClient.TransportGetByDeviceId(deviceId, offset, limit)
	if err != nil {
		return nil, 0, err
	}
	lc.Debugf("transport get by deviceId on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	return transports, totalCount, nil
}

func TransportDelete(deviceId, eventId string, ctx context.Context, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	err := dbClient.TransportDelete(deviceId, eventId)
	if err != nil {
		return err
	}
	lc.Debugf("transport delete on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	return nil
}

func TransportUpdate(deviceId string, d models.Transport, ctx context.Context, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	err := dbClient.TransportUpdate(deviceId, d)
	if err != nil {
		return err
	}
	lc.Debugf("transport update on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	return nil
}
